import React from 'react';
import {
  Form, Input, Button, Select, message, Upload,
} from 'antd';
import { createImage } from 'services/image';

// TODO: refine the regex here
const imagePattern = /^[a-z0-9]+(?:[._-]{1}[a-z0-9]+)*(:[a-z0-9]+)$/;
const { Option } = Select;
const { TextArea } = Input;

class Creation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      exeFile: [],
      apiFile: [],
    };
  }

  uploadImage = async () => {
    const {
      form: { getFieldsValue, validateFieldsAndScroll },
      updateTable,
      changeVisible,
      setUploading,
    } = this.props;
    try {
      await validateFieldsAndScroll();
      this.setState({ loading: true });
      changeVisible(false);
      setUploading(true);
      message.info('上传中, 请勿刷新或关闭页面...');
      const {
        tag, language, description, apiFile, exeFile,
      } = getFieldsValue();
      const formData = new FormData();
      formData.append('exeFile', exeFile.fileList[0].originFileObj);
      formData.append('apiFile', apiFile.fileList[0].originFileObj);
      formData.append('tag', tag);
      formData.append('language', language);
      formData.append('description', description);
      await createImage(formData);
      setUploading(false);
      message.success('上传成功！');
      this.setState({ loading: false });
      updateTable();
      // changeVisible(false);
    } catch (err) {
      console.warn(err);
    }
  };

  validateImageTag = (rule, value, callback) => {
    if (value && !imagePattern.test(value)) {
      callback('镜像名称不合规! (需包含命名及标签部分。'
        + '命名部分应只包含小写字母数字与连接符（"-", "." 或 "_"），'
        + '不能以连接符开始或结束， 且连接符不能连续出现；'
        + '标签部分可包含小写字母数字；命名部分与标签部分之间用 ":" 分隔开)。例：my-image:latest');
    }
    callback();
  }

  validateExeFilenameSuffix = (rule, value, callback) => {
    if (value) {
      if (value.fileList.length > 0) {
        const filename = value.fileList[0].name;
        if (!filename.endsWith('.jar')) {
          callback('文件应为 jar 格式！');
        }
      } else {
        // clear file list in Upload component
        this.setState({ exeFile: [] });
      }
    }
    callback();
  }

  validateApiFilenameSuffix = (rule, value, callback) => {
    if (value) {
      if (value.fileList.length > 0) {
        const filename = value.fileList[0].name;
        if (!filename.endsWith('.yaml') && !filename.endsWith('.yml')) {
          callback('文件应为 yaml 格式！');
        }
      } else {
        this.setState({ apiFile: [] });
      }
    }
    callback();
  }

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { exeFile, apiFile, loading } = this.state;

    return (
      <Form>
        <Form.Item label="镜像名称">
          {getFieldDecorator('tag', {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                message: '请输入镜像名称!',
              },
              {
                validator: this.validateImageTag,
              },
            ],
          })(<Input />)}
        </Form.Item>
        <Form.Item label="语言">
          {getFieldDecorator('language', {
            initialValue: 'java8',
          })(
            <Select placeholder="语言（默认为 java8）">
              <Option key="java8">java8</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item label="镜像描述">
          {getFieldDecorator('description')(
            <TextArea placeholder="镜像描述" />,
          )}
        </Form.Item>
        <Form.Item label="镜像文件">
          {getFieldDecorator('exeFile', {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                message: '请选择文件!',
              },
              {
                validator: this.validateExeFilenameSuffix,
              },
            ],
          })(
            <Upload
              customRequest={() => {}} // 覆盖默认上传事件
              beforeUpload={(f) => this.setState({ exeFile: [f] })}
              fileList={exeFile}
            >
              <Button icon="upload">选择可执行文件</Button>
            </Upload>,
          )}
        </Form.Item>
        <Form.Item label="接口描述文件">
          {getFieldDecorator('apiFile', {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                message: '请选择文件!',
              },
              {
                validator: this.validateApiFilenameSuffix,
              },
            ],
          })(
            <Upload
              customRequest={() => {}} // 覆盖默认上传事件
              beforeUpload={(f) => this.setState({ apiFile: [f] })}
              fileList={apiFile}
            >
              <Button icon="upload">选择接口描述文件</Button>
            </Upload>,
          )}
        </Form.Item>
        <Form.Item>
          <Button onClick={this.uploadImage} loading={loading}>
            提交
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

export default Form.create({})(Creation);
